//
//  SWList.m
//  BeautyGuessFree
//
//  Created by Charles How on 12-4-11.
//  Copyright (c) 2012年 hust. All rights reserved.
//

#import "SWList.h"

#import "storage.h"

@implementation SWList


@synthesize mData;
@synthesize mSWCount;
@synthesize mSWList;

@synthesize mbThreadOver;

static SWList* _sharedSWList = nil;  
+(SWList*)sharedInstance  
{  
	@synchronized([SWList class])  
	{  
		if (!_sharedSWList)  
		{
			[[self alloc] init];  
		}
		
		return _sharedSWList;  
	}  
	
	return nil;  
}  


+(id)alloc  
{  
	@synchronized([SWList class])  
	{  
		NSAssert(_sharedSWList == nil, @"Attempted to allocate a second instance of a singleton.");  
		_sharedSWList = [super alloc];
        
		return _sharedSWList;  
	}  
	
	return nil;  
}  


-(void)startThreadToGetList
{
      [NSThread detachNewThreadSelector:@selector(getList) toTarget:self withObject:nil];
}


-(void)getList
{
    ///auto realse pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //set flag
    mbThreadOver=false;
    
    NSArray * array=[self getDownloadDataByFile];
    
    
	if ( array != nil )
    {
        ///读取保存过得数据
        mSWList=[[NSMutableArray alloc] initWithArray:array];
        mSWCount = [mSWList count];
        myNSLog(@"getList--------mSWCount---=%d",mSWCount);
    }
    else{
        //从网络申请新的数据
        NSString * urlStr=kRequestURL;
        // 初始化请求  
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
        // 设置URL  
        [request setURL:[NSURL URLWithString:urlStr]];  
        // 设置HTTP方法  
        [request setHTTPMethod:@"POST"]; 
        // 发 送同步请求, 这里得returnData就是返回得数据了  
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request   
                                                   returningResponse:nil error:nil];
        //分析数据
        mData = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
        
        // 释放对象  
        [request release];  
        
        
        [self parseData:mData];  //13=1+12
    }
    
    
    
    
    
    ///set flag
    mbThreadOver=true;
    
    /////////
    [pool release];
}


/*
 NSString *jsonstring = [NSString stringWithFormat:@"http://.....xxx"];
 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:jsonstring]];
 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
 NSString *str = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
 NSDictionary *data = [[str JSONValue] retain]
 NSLog(@"%@",str);
 NDlog(@"%@",data);
 
 添加JSON库，取JSON字符串，然后转为你需要的对象
 */
-(void)parseData:(NSString *)dataPayload
{
    NSDictionary *jsonData = [dataPayload JSONValue];
    NSString * str=[jsonData objectForKey:@"resultCount"];
    myNSLog(@"mSWCount>>>>>=====%@",str);
    
    if (str == nil) {
        return;
    }
    
    mSWCount=[str intValue]-1;
    
    NSArray *infoArray = [jsonData objectForKey:@"results"];  //13=1+12
    /*
     NSDictionary *releaseInfo = [infoArray objectAtIndex:0];  
     NSString *latestVersion = [releaseInfo objectForKey:@"version"];  
     NSString *trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];  
     NSString *trackId=[releaseInfo objectForKey:@"trackId"];
     myNSLog(@"trackViewUrl>>>>>=====%@",trackViewUrl);
     myNSLog(@"trackId>>>>>=====%@",trackId);
     
     UIApplication *application = [UIApplication sharedApplication];
     NSString * ViewURL=[NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%@",trackId];
     
     [application openURL:[NSURL URLWithString:trackViewUrl]];  
     */
    
    mSWList = [[NSMutableArray alloc] init];
    for (int i=0; i<mSWCount; i++) {
        //0 to 11
        NSDictionary *releaseInfo = [infoArray objectAtIndex:(i+1)];  //1 to 12
        //NSString *artworkUrl60 = [releaseInfo objectForKey:@"artworkUrl60"]; //image,57X57
        NSString *artworkUrl60 = [releaseInfo objectForKey:@"artworkUrl512"]; //image,512X512
        NSString *trackName = [releaseInfo objectForKey:@"trackName"];  
        NSString *latestVersion = [releaseInfo objectForKey:@"version"];  
        NSString *trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];  
        NSString *trackId=[releaseInfo objectForKey:@"trackId"];
        
        
        
        
        SW_ITEM * item= [[SW_ITEM alloc] init];
        
        
        //image
        NSURL *url = [[NSURL alloc] initWithString:artworkUrl60];
        NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
        if (imageData == nil) {
            ////下载失败则重试3次
            for (int i=0; i<3; i++) {
                imageData = [[NSData alloc] initWithContentsOfURL:url];
                if (imageData != nil) {
                    break;
                }
            }
            
            ///还是为空，则返回
            if (imageData == nil) {
                //认为本次下载失败，不存储数据
                return; 
            }
        }
        //item.image=[[UIImage alloc] initWithData:imageData];
        item.imageData=imageData;
        item.name=trackName;
        item.Id=trackId;
        item.url=trackViewUrl;
        
        [mSWList addObject:item];
        [item release];
        
        myNSLog(@"parseData--------mSWCount-=%d,current index=%d done!\n",mSWCount,i);
    }
    
    if (mSWCount >=1) {
        ///分析完毕
        
        //对数组进行重新排序
        [self sortByCurrentLanguage];
        //[self sortArrayChineseInTop:&mSWList]; //中文排到英文最上面
        //[self sortArrayChineseFreeInTop:&mSWList]; //中文版排到中文免费上面，最下面是英文
        //[self sortArrayEnglishInTop:&mSWList];//英文的排上面
        
        
        [self saveDownloadDataByFile];
    }
    
}


#pragma mark save & get data by UserDefaults
/*=======================================================
 成功返回array，否则返回nil
 ========================================================*/
-(id)getDownloadDataByUserDefaults
{
    NSArray * retArray=nil;
    
 	NSUserDefaults	*userDefault = [NSUserDefaults standardUserDefaults];	
    
    NSData *udObject=[userDefault objectForKey:kSWList];
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ;
	//NSArray * array =[userDefault objectForKey:kSWList];
    //int count=[userDefault integerForKey:kSWCount];
    myNSLog(@">>>>>>>>>>>>>getList--------array---=%@",array);
    
    ////获取当前版本信息
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];  
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
    NSString *savedVersion =[userDefault objectForKey:kSWListVersion]; //获得保存的版本信息
    
    bool bSameVersion=false;
    if (savedVersion != nil) {
        bSameVersion=[savedVersion isEqualToString:currentVersion];
    }
    
    
	if ( array != nil && (bSameVersion == true) )
    {
        retArray=array;
    }   
    
    
    return retArray;
}



-(void)saveDownloadDataByUserDefaults
{
    //将网络数据存进NSUserDefaults
    NSUserDefaults	*userDefault = [NSUserDefaults standardUserDefaults];
    NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:mSWList];  
    [userDefault setObject:udObject forKey:kSWList];
    
    ////获取当前版本信息
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];  
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
    [userDefault setObject:currentVersion forKey:kSWListVersion];
    
    myNSLog(@"getList--------mSWCount-insert--=%d",mSWCount);
    [userDefault synchronize];
}



#pragma mark save & get data by File
-(NSArray *)getDownloadDataByFile
{
    NSArray * retArray=nil;
    
    //load
    NSString *filename = [storage dataFilePathCommon:kSaveFileName]; 
    myNSLog(@"list path=%@",filename);
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
    
    if (arr == nil) {
        return nil;
    }
    
    NSData *udObject = [arr objectAtIndex:0];
    NSString *savedVersion =  [arr objectAtIndex:1];
    
    if (udObject == nil) {
        return nil;
    }
    
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ; //list array
    
    if (array == nil) {
        return nil;
    }
    
    myNSLog(@"link array=%@",array);
    

    
    ////获取当前版本信息
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];  
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];

    
    bool bSameVersion=false;
    if (savedVersion != nil) {
        bSameVersion=[savedVersion isEqualToString:currentVersion];
    }
    
    
	if ( array != nil && (bSameVersion == true) )
    {
        retArray=array;
    }  
    
    return retArray;
}



-(void)saveDownloadDataByFile
{
    /*=======================================================
     NSKeyedArchiver
     ========================================================*/
    
    //将网络数据存
    NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:mSWList];  
    
    ////获取当前版本信息
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];  
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
    
    NSArray *Array = [NSArray arrayWithObjects:udObject, currentVersion, nil];
    
    //Save
    NSString *filename = [storage dataFilePathCommon:kSaveFileName]; 
    [NSKeyedArchiver archiveRootObject:Array toFile:filename];
}



-(BOOL)getThreadOverFlag
{
    return mbThreadOver;
}


-(SWList *) getItemByIndex:(int)index
{
    
    assert(index >=0 && index < mSWCount);
    assert(mSWList != nil);
    return [mSWList objectAtIndex:index];
}


#pragma mark check include Chinese
-(BOOL)checkIncludeChinese:(NSString *) text
{
    int length = [text length];
    BOOL bRtn=false;
    
    for (int i=0; i<length; ++i)
    {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [text substringWithRange:range];
        const char    *cString = [subString UTF8String];
        if (strlen(cString) == 3)
        {
            NSLog(@"汉字:%s", cString);
            bRtn=true;
            break;
        }
    }
    
    return bRtn;
}


#pragma mark sort
-(void)sortByCurrentLanguage
{
    //获取当前语言   
    
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];  
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString *current = [languages objectAtIndex:0];
    
    if ([current isEqualToString:@"zh-Hans"]) {//中文
        //strReturn = NSLocalizedStringFromTable(str, Chinese, str);
        
        [self sortArrayChineseInTop:&mSWList]; //中文排到英文最上面
        [self sortArrayChineseFreeInTop:&mSWList]; //中文版排到中文免费上面，最下面是英文
        //[self sortArrayEnglishInTop:&mSWList];//英文的排上面
        
    }else if([current isEqualToString:@"en"]){//英文
        //strReturn = NSLocalizedStringFromTable(str, English,str);
        
        //[self sortArrayChineseInTop:&mSWList]; //中文排到英文最上面
        //[self sortArrayChineseFreeInTop:&mSWList]; //中文版排到中文免费上面，最下面是英文
        [self sortArrayEnglishInTop:&mSWList];//英文的排上面
    }   
}


-(void)sortArrayChineseInTop:(NSMutableArray **)array
{
    assert(array != nil);
    assert(*array != nil);
    
    BOOL bChange=false;
    
    int count=[*array count];
    for (int i=0; i<count; i++) {
        SW_ITEM * aSW_ITEM=[*array objectAtIndex:i];
        BOOL aChinese=[self checkIncludeChinese:aSW_ITEM.name];
        
        
        ///如果不含有中文
        if (!aChinese) {
            ///寻找第一个包含中文的名字，替换位置
            for (int j=i+1; j<count; j++) {
                SW_ITEM * bSW_ITEM=[*array objectAtIndex:(j)];
                BOOL bChinese=[self checkIncludeChinese:bSW_ITEM.name];
                
                if (bChinese) {
                    //交换i ，j的位置上的元素
                    SW_ITEM * tmp=[[SW_ITEM alloc] init];
                    
                    tmp.imageData=aSW_ITEM.imageData;
                    tmp.name=aSW_ITEM.name;
                    tmp.Id=aSW_ITEM.Id;
                    tmp.url=aSW_ITEM.url;
                    
                    [*array replaceObjectAtIndex:i withObject:bSW_ITEM];
                    [*array replaceObjectAtIndex:j withObject:tmp];
                    //aSW_ITEM=bSW_ITEM;
                    //bSW_ITEM=tmp;
                    [tmp release];
                    
                    bChange=true;
                    break;
                }
                
                
                
            }//end for
            
            if (bChange == false) {
                break;
            }
            
        }
    }
    
}



-(void)sortArrayChineseFreeInTop:(NSMutableArray **)array
{
    assert(array != nil);
    assert(*array != nil);
    
    BOOL bChange=false;
    
    int count=[*array count];
    for (int i=0; i<count; i++) {
        SW_ITEM * aSW_ITEM=[*array objectAtIndex:i];
        BOOL aChinese=[self checkIncludeChinese:aSW_ITEM.name];
        
        
        ///如含有中文
        if (aChinese) {
            
            if ([aSW_ITEM.name rangeOfString:@"免费版"].length > 0) {
                ///含有免费版三个字，交换到下面去
                ///寻找第一个不包含"免费版"的中文的名字，替换位置
                for (int j=i+1; j<count; j++) {
                    SW_ITEM * bSW_ITEM=[*array objectAtIndex:(j)];
                    BOOL bChinese=[self checkIncludeChinese:bSW_ITEM.name];
                    
                    if (bChinese) {
                        if([bSW_ITEM.name rangeOfString:@"免费版"].length <= 0){
                            ///不含油“免费版”三个字
                            //交换i ，j的位置上的元素
                            SW_ITEM * tmp=[[SW_ITEM alloc] init];
                            
                            tmp.imageData=aSW_ITEM.imageData;
                            tmp.name=aSW_ITEM.name;
                            tmp.Id=aSW_ITEM.Id;
                            tmp.url=aSW_ITEM.url;
                            
                            [*array replaceObjectAtIndex:i withObject:bSW_ITEM];
                            [*array replaceObjectAtIndex:j withObject:tmp];
                            //aSW_ITEM=bSW_ITEM;
                            //bSW_ITEM=tmp;
                            [tmp release];
                            
                            bChange=true;
                            break;
                        }
                        
                        
                    }
                    
                    
                    
                }//end for
                
                if (bChange == false) {
                    break;
                }
                
            }
            
            
        }
    }
    
}


///英文的排上面
-(void)sortArrayEnglishInTop:(NSMutableArray **)array
{
    assert(array != nil);
    assert(*array != nil);
    
    BOOL bChange=false;
    
    int count=[*array count];
    for (int i=0; i<count; i++) {
        SW_ITEM * aSW_ITEM=[*array objectAtIndex:i];
        BOOL aChinese=[self checkIncludeChinese:aSW_ITEM.name];
        
        
        ///如果含有中文
        if (aChinese) {
            ///寻找第一个不包含中文的名字，替换位置
            for (int j=i+1; j<count; j++) {
                SW_ITEM * bSW_ITEM=[*array objectAtIndex:(j)];
                BOOL bChinese=[self checkIncludeChinese:bSW_ITEM.name];
                
                if (!bChinese) {
                    //交换i ，j的位置上的元素
                    SW_ITEM * tmp=[[SW_ITEM alloc] init];
                    
                    tmp.imageData=aSW_ITEM.imageData;
                    tmp.name=aSW_ITEM.name;
                    tmp.Id=aSW_ITEM.Id;
                    tmp.url=aSW_ITEM.url;
                    
                    [*array replaceObjectAtIndex:i withObject:bSW_ITEM];
                    [*array replaceObjectAtIndex:j withObject:tmp];
                    //aSW_ITEM=bSW_ITEM;
                    //bSW_ITEM=tmp;
                    [tmp release];
                    
                    bChange=true;
                    break;
                }
                
                
                
            }//end for
            
            if (bChange == false) {
                break;
            }
            
        }
    }
    
}



-(int)getSWCount
{
    return mSWCount;
}



@end
